/*
 * SimpleMapAdaptor.java
 *
 * Created Oct 10, 2006
 * David Connell
 * Copyright (c) 2005 Synergy Systems, Inc
 */
package org.puresilk.afx.xmlbeans;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.jdom.Attribute;
import org.jdom.Element;

/**
 * A simple adaptor to allow Mapped collections to 
 * be loaded and extracted from XMLBeans.  The simple
 * part means that there is no nesting or other text 
 * nodes etc, just for mapping all attributes of the 
 * current node.  
 * 
 * TODO: MapAdaptor with nested element maps etc.
 * 
 */
public class SimpleMapAdaptor extends Adaptable {
	
	/** convert xml attributes to mapping */
	public Map<String,String> to_map() {
		// create container
		Map<String,String> map = new HashMap<String,String>();

		// retrieve and verify content as xml
		Element el = to_xml();
		if(el == null)
			return null;
	
		// extract attributes and store in map
		Iterator itr = el.getAttributes().iterator();
		while(itr.hasNext()) {
			Attribute attr = (Attribute)itr.next();
			map.put(attr.getName(),attr.getValue());
		}
		
		// return attribute mapping
		return map;
	}
	
	/** default to an xmlbean element type */
	public void from_map(Map<String,String> map){
		from_map("xmlbean",map);
	}
	
	/** generate an XML node with name and mapped attributes */
	public void from_map(String name, Map<String,String> map) {
		Element xml = new Element(name);
		Iterator itr = map.keySet().iterator();
		while(itr.hasNext()){
			String key = (String)itr.next();
			String val = (String)map.get(key);
			xml.setAttribute(key,val);
		}
		
		// send xml to waiting bean
		from_xml(xml);		
	}
}
